import uuid
import time
import hashlib

import requests
import json
import base64
import time


def encode_base64(raw_text):
    return str(base64.b64encode(json.dumps(raw_text, sort_keys=True).encode('utf-8')), encoding="utf8")


def decode_base64(raw_text):
    return str(base64.b64decode(raw_text), "utf-8")


def cal_md5(raw_text_list):
    return hashlib.md5(bytes(raw_text_list, encoding="utf8")).hexdigest()


def get_capability_name_24(raw_capabilityname):
    """
    capabilityname需24位，不足补0.
    """
    capabilityname_list = list(raw_capabilityname)
    while len(capabilityname_list) != 24:
        capabilityname_list.append("0")
    capabilityname = "".join(capabilityname_list)
    return capabilityname


def gen_result(prompt, user_input):
    # 1. 鉴权信息
    url = 'http://172.21.158.138:9050/bigmodel_infer_gateway/v1/service'  # 根据实际情况填写IP以及端口以及API接口
    appid = "csylznsc" # 填写获取到的appID
    appkey = 'a7ce949c54b10f94312691dde0f2e73ec' # 填写获取到的appKey
    
    capabilityname = "semantic0000000000000000"
    _uuid = "".join(str(uuid.uuid4()).split('-'))

    capabilityname = get_capability_name_24(capabilityname)

    # 2. 设置请求头参数
    X_Server_Param = {
        "appid": f"{appid}",
        "csid": f"{appid}{capabilityname}{_uuid}",
    }

    X_Server_Param = encode_base64(X_Server_Param)
    X_CurTime = str(int(time.time()))
    headers = {
        "Content-Type": "application/json; charset=utf-8",
        "X-Server-Param": X_Server_Param,
        "X-CurTime": X_CurTime,
        "X-CheckSum": cal_md5(appkey + X_CurTime + X_Server_Param),
    }

    # 3. 设置请求体
    messages = [
        {"role": "system", "content": prompt},  # 为了防止响应时间过长，务必将prompt放至system对应的content中
        {
            "role": "user",
            "content": content  # 输入的问题
        }
    ]
        
    body = {
        "messages": messages,  # 必需值
        "model": "QWen2-72B-Instruct-GPTQ-Int4", # 调用的模型
        "max_tokens": 1024, # 非必需值，生成响应的最大令牌数
        "stream": False, # 非流式请求
        "temperature": 0.1 # 非必需值，采样温度，控制模型输出的随机性
    }

    # 4. 处理响应
    try:
        print("执行到这里啦。。。")
        response = requests.post(url, json=body, headers=headers)
        response_data = response.json()

        # 4.1 判断输入的问题或者模型输出的结果是否符合安全要求
        # if response_data['choices'][0]['finish_reason'] == 'content_filter':
        #     # 不符合安全要求，可根据实际情况进一步处理
        #     pass
        # else:
        #     # 符合安全要求，返回模型回答结果（也可根据实际情况返回其他信息或做进一步处理）
        #     return response_data['choices'][0]['message']['content']

    except Exception as e:
        print(f"{'-' * 10}\n 错误：{e}\n{'-' * 10}")


if __name__ == '__main__':
    # 为了方便演示，直接将提示词赋值给了prompt。若提示词较长，可考虑使用文件存放然后从文件中读取
    print('执行到这里')
    prompt = '你是一个测试工程师'
    content = '请帮我设计网页登录页面的测试用例，并输出用例列表'# 输入的问题

    start_time = time.time()

    result = gen_result(prompt, content)
    print(result)

    end_time = time.time()

    print(f"用时：{end_time - start_time}")
